/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/12 18:12
@File     : database.go
@Project  : gohub
@Desc     :
*/
package bootstap

import (
	"errors"
	"fmt"
	"gohub/pkg/config"
	"gohub/pkg/database"
	"gohub/pkg/logger"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"time"
)

// 初始化数据库、orm
func SetupDB() {
	var dbConfig gorm.Dialector
	switch config.Get("database.connection") {
	case "mysql":
		//构建dsn
		dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&multiStatements=true&loc=Local", config.Get("database.mysql.username"), config.Get("database.mysql.password"), config.Get("database.mysql.host"), config.Get("database.mysql.port"), config.Get("database.mysql.database"), config.Get("database.mysql.charset"))
		dbConfig = mysql.New(mysql.Config{
			DSN: dsn,
		})
	case "sqlite":
		//"初始化sqlite"
		database := config.Get("database.sqlite.database")
		dbConfig = sqlite.Open(database)
	default:
		panic(errors.New("不支持的数据库"))
	}
	//链接数据库，并设置gorm的日志模式
	database.Connect(dbConfig, logger.NewGormLogger())

	//设置最大连接数
	database.SQLDB.SetMaxOpenConns(config.GetInt("database.mysql.max_open_connections"))
	//设置最大空闲连接数
	database.SQLDB.SetMaxIdleConns(config.GetInt("database.mysql.max_idle_connections"))
	//设置每个链接的过期时间
	database.SQLDB.SetConnMaxLifetime(time.Duration(config.GetInt("database.mysql.max_life_seconds")) * time.Second)

	//database.DB.AutoMigrate(&user.User{})
}
